const requestHelper = require('../../utils/request');
const buildUrl = requestHelper.buildUrl || ((url) => url);

Page({
  data: {
    orderId: '',
    orderInfo: {},
    courierInfo: {},

    // 评价数据
    overallRating: 0,
    speedRating: 0,
    attitudeRating: 0,
    comment: '',
    isAnonymous: false,

    // 评价文本
    ratingTexts: [
      '非常不满意',
      '不满意',
      '一般',
      '满意',
      '非常满意'
    ],
    speedTexts: [
      '非常慢',
      '比较慢',
      '一般',
      '比较快',
      '非常快'
    ],
    attitudeTexts: [
      '态度很差',
      '态度一般',
      '态度正常',
      '态度友好',
      '态度非常好'
    ],

    // 快捷标签
    quickTags: [
      { text: '速度很快', selected: false },
      { text: '服务热情', selected: false },
      { text: '包装完好', selected: false },
      { text: '沟通顺畅', selected: false },
      { text: '准时送达', selected: false },
      { text: '价格合理', selected: false }
    ],

    // 提交状态
    isSubmitting: false,
    showSuccessModal: false
  },

  onLoad(options) {
    const { orderId } = options;
    if (!orderId) {
      wx.showToast({ title: '订单信息错误', icon: 'none' });
      wx.navigateBack();
      return;
    }

    this.setData({ orderId });
    this.loadOrderInfo();
  },

  // 加载订单信息
  async loadOrderInfo() {
    try {
      const res = await this.request({
        url: `/api/orders/${this.data.orderId}`,
        method: 'GET'
      });

      if (res && res.success) {
        const raw = res.data || {};
        // 兼容多种返回结构：data 本身是订单，或 data.order 才是订单
        const orderInfo = raw.order || raw;
        const courierInfo = raw.courier || {};

        if (!orderInfo) {
          wx.showToast({ title: '订单信息异常', icon: 'none' });
          wx.navigateBack();
          return;
        }

        const completedAtRaw = orderInfo.completed_at || orderInfo.completedAt || '';

        // 归一化部分字段，便于 WXML 使用
        const normalizedOrder = {
          ...orderInfo,
          completedAt: this.formatTime(completedAtRaw),
          finalFee: orderInfo.finalFee || orderInfo.final_fee || orderInfo.suggested_fee || orderInfo.amount || 0,
          deliveryAddress: orderInfo.deliveryAddress || orderInfo.delivery_address || ''
        };

        this.setData({
          orderInfo: normalizedOrder,
          courierInfo: courierInfo
        });
      } else {
        wx.showToast({ title: '加载订单信息失败', icon: 'none' });
        wx.navigateBack();
      }
    } catch (error) {
      console.error('加载订单信息失败:', error);
      wx.showToast({ title: '网络错误', icon: 'none' });
      wx.navigateBack();
    }
  },

  // 设置总体评分
  setOverallRating(e) {
    const rating = parseInt(e.currentTarget.dataset.rating);
    this.setData({ overallRating: rating });

    // 自动设置分项评分
    if (this.data.speedRating === 0) {
      this.setData({ speedRating: rating });
    }
    if (this.data.attitudeRating === 0) {
      this.setData({ attitudeRating: rating });
    }
  },

  // 设置速度评分
  setSpeedRating(e) {
    const rating = parseInt(e.currentTarget.dataset.rating);
    this.setData({ speedRating: rating });
  },

  // 设置态度评分
  setAttitudeRating(e) {
    const rating = parseInt(e.currentTarget.dataset.rating);
    this.setData({ attitudeRating: rating });
  },

  // 评论输入
  onCommentInput(e) {
    this.setData({ comment: e.detail.value });
  },

  // 切换标签
  toggleTag(e) {
    const index = e.currentTarget.dataset.index;
    const key = `quickTags[${index}].selected`;
    const selected = !this.data.quickTags[index].selected;

    this.setData({
      [key]: selected
    });

    // 如果选择了标签，自动添加到评论中
    if (selected) {
      const tagText = this.data.quickTags[index].text;
      let newComment = this.data.comment;

      if (newComment) {
        if (!newComment.includes(tagText)) {
          newComment += ' ' + tagText;
        }
      } else {
        newComment = tagText;
      }

      this.setData({ comment: newComment });
    }
  },

  // 切换匿名
  toggleAnonymous(e) {
    this.setData({ isAnonymous: e.detail.value });
  },

  // 提交评价
  async submitRating() {
    const { overallRating, speedRating, attitudeRating } = this.data;
    if (!(overallRating > 0 && speedRating > 0 && attitudeRating > 0)) {
      wx.showToast({ title: '请完成评价', icon: 'none' });
      return;
    }

    this.setData({ isSubmitting: true });

    try {
      const ratingData = {
        order_id: this.data.orderId,
        overall_rating: this.data.overallRating,
        speed_rating: this.data.speedRating,
        attitude_rating: this.data.attitudeRating,
        comment: this.data.comment,
        is_anonymous: this.data.isAnonymous,
        tags: this.data.quickTags
          .filter(tag => tag.selected)
          .map(tag => tag.text)
      };

      const res = await this.request({
        url: '/api/ratings',
        method: 'POST',
        data: ratingData
      });

      if (res.success) {
        this.setData({ showSuccessModal: true });

        // 更新订单评价状态
        wx.setStorageSync('orderRated_' + this.data.orderId, true);
      } else {
        wx.showToast({ title: res.message || '评价失败', icon: 'none' });
      }
    } catch (error) {
      console.error('提交评价失败:', error);
      wx.showToast({ title: '网络错误', icon: 'none' });
    } finally {
      this.setData({ isSubmitting: false });
    }
  },

  // 格式化时间
  formatTime(timestamp) {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  },

  // 返回
  goBack() {
    wx.navigateBack();
  },

  // 跳转到订单列表
  goToOrderList() {
    wx.reLaunch({ url: '/pages/orderList/orderList' });
  },

  // 网络请求封装
  request(options) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: buildUrl(options.url || ''),
        method: options.method || 'GET',
        data: options.data,
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${wx.getStorageSync('token')}`
        },
        success: (res) => {
          resolve(res.data);
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  }
}, {
  // 计算属性
  computed: {
    canSubmit() {
      const { overallRating, speedRating, attitudeRating } = this.data;
      return overallRating > 0 && speedRating > 0 && attitudeRating > 0;
    }
  }
});

// 注入计算属性
(function injectComputed(page) {
  const originalOnLoad = page.onLoad;
  const originalSetData = page.setData;

  page.onLoad = function (options) {
    if (page.computed) {
      const computedKeys = Object.keys(page.computed);
      computedKeys.forEach(key => {
        Object.defineProperty(this.data, key, {
          get: () => page.computed[key].call(this),
          enumerable: true
        });
      });
    }
    originalOnLoad.call(this, options);
  };

  page.setData = function (data, callback) {
    originalSetData.call(this, data, () => {
      if (page.computed) {
        const computedKeys = Object.keys(page.computed);
        const computedData = {};
        computedKeys.forEach(key => {
          computedData[key] = this.data[key];
        });
        originalSetData.call(this, computedData);
      }
      callback && callback();
    });
  };
})(Page);